<template>
  <div class="get-stock-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入产品名称"
            clearable
          />
        </el-form-item>
                 <el-form-item label="单位">
            <el-input
            v-model="searchForm.unitName"
            placeholder="请输入单位"
            clearable
          />
         </el-form-item>
        <el-form-item label="仓库名称">
           <el-input
            v-model="searchForm.depotName"
            placeholder="请输入仓库名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="产品条码">
          <el-input
            v-model="searchForm.barcode"
            placeholder="请输入产品条码"
            clearable
          />
        </el-form-item>
      
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="success" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="stat-card current-stock" v-loading="loading" @click="showStatDetails('currentStock')">
            <div class="stat-number">{{ loading ? '...' : statistics.currentStockCount }}</div>
            <div class="stat-label">当前库存数量</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card current-amount" v-loading="loading" @click="showStatDetails('currentAmount')">
            <div class="stat-number">{{ loading ? '...' : formatCurrency(statistics.currentStockAmount) }}</div>
            <div class="stat-label">当前库存金额</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card inbound" v-loading="loading" @click="showStatDetails('inbound')">
            <div class="stat-number">{{ loading ? '...' : statistics.inboundCount }}</div>
            <div class="stat-label">入库数量</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card outbound" v-loading="loading" @click="showStatDetails('outbound')">
            <div class="stat-number">{{ loading ? '...' : statistics.outboundCount }}</div>
            <div class="stat-label">出库数量</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card pending-inbound" v-loading="loading" @click="showStatDetails('pendingInbound')">
            <div class="stat-number">{{ loading ? '...' : statistics.pendingInboundCount }}</div>
            <div class="stat-label">待入库</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card pending-outbound" v-loading="loading" @click="showStatDetails('pendingOutbound')">
            <div class="stat-number">{{ loading ? '...' : statistics.pendingOutboundCount }}</div>
            <div class="stat-label">待出库</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="exportStatistics">导出统计</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
                 <el-table-column type="selection" width="55" />
         <el-table-column type="index" label="序号" width="100" />
         <el-table-column prop="productCode" label="货品编号" width="150" />
         <el-table-column prop="productName" label="货品名称" width="200" />
         <el-table-column prop="productStatus" label="状态" width="100">
           <template #default="scope">
             <el-tag :type="scope.row.productStatus === 1 ? 'success' : 'danger'">
               {{ scope.row.productStatus === 1 ? '启用' : '停用' }}
             </el-tag>
           </template>
         </el-table-column>
         <el-table-column prop="categoryName" label="货品类型" width="120" />
         <el-table-column prop="specifications" label="规格型号" width="120" />
         <el-table-column prop="unitName" label="单位" width="80" />
         <el-table-column prop="barcode" label="条码" width="150" />
         <el-table-column prop="depotName" label="仓库名称" width="120" />
         <el-table-column prop="locationName" label="库位名称" width="120" />
         <el-table-column prop="stocknum" label="当前库存" width="100" />
         <el-table-column prop="stockMoney" label="库存金额" width="120" />
       
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-info">总{{ total }}条</span>
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[15, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { http } from '@/axios/axiosHelpers'

// 搜索表单数据 - 对应后端DTO字段
const searchForm = reactive({
  productName: '',      // 对应ProductName
  categoryName: '',     // 对应CategoryName
  unitName: '',         // 对应UnitName
  depotName: '',        // 对应DepotName
  barcode: '',          // 对应Barcode
  showDisabled: false,
  filterZeroStock: false
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 15
})

// 定义数据类型 - 对应后端StockDTO
interface StockItem {
  id: number                    // 产品Id
  productId: number             // 产品编号
  productCode: string           // 产品名称
  productName: string           // 产品状态
  productStatus: number         // 产品状态
  categoryId: number            // 类别编号
  categoryName: string          // 类别名称
  specifications: string        // 产品规格
  unitId: number               // 单位编号
  unitName: string             // 单位名称
  barcode: string              // 条码
  depotId: number              // 仓库编号
  depotName: string            // 仓库名称
  locationId: number           // 库位编号
  locationName: string         // 库位名称
  stockId: number              // 库存Id
  stocknum: number             // 当前库存
  stockMoney: number           // 库存金额
}

// 表格数据
const tableData = ref<StockItem[]>([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref<StockItem[]>([])

// 统计数据
const statistics = ref({
  currentStockCount: 0,      // 当前库存数量
  currentStockAmount: 0,     // 当前库存金额
  inboundCount: 0,           // 入库数量
  outboundCount: 0,          // 出库数量
  pendingInboundCount: 0,    // 待入库数量
  pendingOutboundCount: 0    // 待出库数量
})


import Purchase from '@/http/PurSale'

// 格式化货币显示
const formatCurrency = (amount: number): string => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2
  }).format(amount)
}

// 计算统计数据
const calculateStatistics = (data: StockItem[]) => {
  const stats = {
    currentStockCount: 0,
    currentStockAmount: 0,
    inboundCount: 0,
    outboundCount: 0,
    pendingInboundCount: 0,
    pendingOutboundCount: 0
  }
  
  data.forEach(item => {
    // 当前库存数量和金额
    stats.currentStockCount += item.stocknum || 0
    stats.currentStockAmount += item.stockMoney || 0
    
    // 根据产品状态和库存情况计算统计
    if (item.productStatus === 1) {
      // 启用状态的产品
      if (item.stocknum > 0) {
        // 有库存的启用产品计入入库数量
        stats.inboundCount += item.stocknum
      } else {
        // 无库存的启用产品计入待入库
        stats.pendingInboundCount += 1
      }
    } else {
      // 停用状态的产品
      if (item.stocknum > 0) {
        // 有库存的停用产品计入出库数量
        stats.outboundCount += item.stocknum
      } else {
        // 无库存的停用产品计入待出库
        stats.pendingOutboundCount += 1
      }
    }
  })
  
  return stats
}

// 调用后台API接口
const fetchStockData = async () => {
  loading.value = true
  try {
         // 构建请求参数 - 对应后端API参数
     const params = {
       PageIndex: pagination.pageIndex,
       PageSize: pagination.pageSize,
       ProductName: searchForm.productName,
       UnitName: searchForm.unitName,
       Barcode: searchForm.barcode,
       DepotName: searchForm.depotName
     }

         // 调用后台API
     const response = await http.get('/scmreadconsul/api/Ledger/ShowStock', { params })
     
     console.log('API请求参数:', params)
     console.log('API响应数据:', response.data)
     
     if (response.data.code === 200) {
       tableData.value = response.data.items || []
       total.value = response.data.totalCount || 0
       
       // 计算统计数据
       statistics.value = calculateStatistics(tableData.value)
       
       console.log('成功获取数据，条数:', tableData.value.length)
       console.log('统计数据:', statistics.value)
       ElMessage.success(response.data.msg || '获取数据成功')
     } else {
       // 如果API调用失败，使用模拟数据
     
       total.value = 100
       ElMessage.warning('API调用失败，显示模拟数据')
       console.warn('API响应格式异常:', response.data)
     }
      } catch (error: any) {
     console.error('获取库存数据失败:', error)
     console.error('错误详情:', error.response?.data || error.message)
     // 使用模拟数据
   
     total.value = 100
     // 计算模拟数据的统计数据
     statistics.value = calculateStatistics(tableData.value)
     ElMessage.error(`网络错误: ${error.response?.data?.message || error.message}，显示模拟数据`)
   } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchStockData()
}

// 重置处理
const handleReset = () => {
  Object.assign(searchForm, {
    productName: '',
    categoryName: '',
    unitName: '',
    depotName: '',
    barcode: '',
    showDisabled: false,
    filterZeroStock: false
  })
  pagination.pageIndex = 1
  fetchStockData()
}



// 刷新处理
const handleRefresh = () => {
  fetchStockData()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchStockData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchStockData()
}

// 选择行改变
const handleSelectionChange = (selection: StockItem[]) => {
  selectedRows.value = selection
}

// 显示统计详情
const showStatDetails = (type: string) => {
  const statLabels = {
    currentStock: '当前库存数量',
    currentAmount: '当前库存金额',
    inbound: '入库数量',
    outbound: '出库数量',
    pendingInbound: '待入库',
    pendingOutbound: '待出库'
  }
  
  const statValues = {
    currentStock: statistics.value.currentStockCount,
    currentAmount: formatCurrency(statistics.value.currentStockAmount),
    inbound: statistics.value.inboundCount,
    outbound: statistics.value.outboundCount,
    pendingInbound: statistics.value.pendingInboundCount,
    pendingOutbound: statistics.value.pendingOutboundCount
  }
  
  ElMessage.info(`${statLabels[type as keyof typeof statLabels]}: ${statValues[type as keyof typeof statValues]}`)
}

// 导出统计数据
const exportStatistics = () => {
  const statsData = {
    当前库存数量: statistics.value.currentStockCount,
    当前库存金额: formatCurrency(statistics.value.currentStockAmount),
    入库数量: statistics.value.inboundCount,
    出库数量: statistics.value.outboundCount,
    待入库: statistics.value.pendingInboundCount,
    待出库: statistics.value.pendingOutboundCount,
    导出时间: new Date().toLocaleString('zh-CN')
  }
  
  // 创建CSV内容
  const csvContent = Object.entries(statsData)
    .map(([key, value]) => `${key},${value}`)
    .join('\n')
  
  // 创建下载链接
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `库存统计_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('统计数据导出成功')
}



// 组件挂载时获取数据
onMounted(() => {
  fetchStockData()
  
  // 每5分钟自动刷新统计数据
  setInterval(() => {
    fetchStockData()
  }, 5 * 60 * 1000)
})
</script>

<style scoped>
.get-stock-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.current-stock .stat-number {
  color: #409eff;
}

.current-amount .stat-number {
  color: #409eff;
}

.inbound .stat-number {
  color: #67c23a;
}

.outbound .stat-number {
  color: #e6a23c;
}

.pending-inbound .stat-number {
  color: #67c23a;
}

.pending-outbound .stat-number {
  color: #e6a23c;
}

/* 添加数字变化动画 */
.stat-number {
  animation: numberChange 0.5s ease-out;
}

@keyframes numberChange {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.action-buttons {
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
}

.total-info {
  color: #666;
  font-size: 14px;
}

/* 水印样式 */
.get-stock-container::before {
  content: '张海宾 zhanghaibin';
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-45deg);
  font-size: 48px;
  color: rgba(0, 0, 0, 0.1);
  pointer-events: none;
  z-index: -1;
  white-space: nowrap;
}
</style>
